package com.ttbj.controller.driver;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyuncs.exceptions.ClientException;
import com.google.gson.JsonObject;
import com.ttbj.api.driver.DriverService;
import com.ttbj.api.dto.Page;
import com.ttbj.api.dto.SalesmanDto;
import com.ttbj.api.dto.driver.DriverDto;
import com.ttbj.api.exception.BusinessException;
import com.ttbj.constant.Const;
import com.ttbj.constant.PlatFormErrorCode;
import com.ttbj.constant.annotation.SystemControllerLog;
import com.ttbj.constant.driver.DriverToExamineEnum;
import com.ttbj.core.util.JsonTools;
import com.ttbj.util.ShortDriverSendSMSUtil;
import com.ttbj.util.ViewDataUtil;


@Controller
public class DriverController {
	
	private static final Logger logger = LoggerFactory.getLogger(DriverController.class);
	@Autowired
	private DriverService driverService;
	
	
	
	/**
	 * 司机列表页面
	 * @return
	 */
	@RequestMapping(value="/driver/short_driver_list.htm")
	public String short_driver_list() {
		return "driver/short_driver_list";
	}
	
	/**
	 * 增加司机页面
	 * @return
	 */
	@RequestMapping(value="/driver/short_edit_driver.htm")
	public String short_edit_driver() {
		return "driver/short_edit_driver";
	}
	
	/**
	 * 
	 * @return
	 */
	@RequestMapping(value="/driver/shortdriver_info.htm")
	public String shortdriver_info() {
		return "driver/shortdriver_info";
	}
	
	/**
	 * 司机账户查询页面
	 * @return
	 */
	@RequestMapping(value="/driver/driver_acc_query.htm")
	public String driver_acc_query() {
		return "driver/driver_acc_query";
	}
	
	/**
	 * 司机余额查询页面
	 * @return
	 */
	@RequestMapping(value="/driver/driver_balance.htm")
	public String driver_balance() {
		return "driver/driver_balance";
	}
	
	/**
	 * 分页查询公司下所有司机的信息
	 * @param request
	 * @param page 分页
	 * @param driverDto 司机信息
	 * @return 司机list
	 */
	@RequestMapping(value="/driver/getDriverInfoByPage.htm", method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	public String getDriverInfoByPage(HttpServletRequest request, Page page, DriverDto driverDto) {
		//获取当前登录的用户信息
		SalesmanDto salesmanDto = (SalesmanDto) request.getSession().getAttribute(Const.TTBJ_USER_SESSION_KEY);
		//获取公司编号
		String companyNum = salesmanDto.getSalesmanComnum();
		List<DriverDto> driverDtos = this.driverService.findDriverInfoByPage(page, driverDto, companyNum);
		int count = 0;
		if (null != driverDtos) {
			count = this.driverService.findDriverInfoByPageCount(driverDto, companyNum);
		}
		return ViewDataUtil.buildSuccessPageJson("司机信息", driverDtos, count);
	}
	
	 /**
     * 查询司机用户名是否使用
     * @param fieldId 
     * @param fieldValue
     * @return 
     */
    @RequestMapping(value="/driver/getDriverNameCheck.htm", method=RequestMethod.GET, produces={"text/html;charset=UTF-8;","application/json;"})
    @ResponseBody
    public String getDriverNameCheck(HttpServletRequest request, @RequestParam String fieldId, @RequestParam String fieldValue) {
    	boolean flag = true;
    	Object[] objects = new Object[3];
    	objects[0] = fieldId;
    	//先检测司机中是否已经存在这个用户名
    	int driverCount = this.driverService.findDriverInfoExist(fieldValue);
    	//如果driverCount == 0，则说明长途司机用户不存在，直接返回true
    	if (driverCount == 0) {
    		objects[1] = flag;
    		objects[2] = "* ok";
		}else {
			flag = false;
			objects[1] = flag;
			objects[2] = "* 该用户名已存在";
		}
    	//返回的内容为：[String,Boolean] String是接收到的fieldId的值。Boolean，验证通过返回true，不通过返回false
    	String result = "[\"" + objects[0] + "\"," + objects[1] + ",\"" + objects[2] + "\"]";
    	return result;
    }
	
	/**
	 * 增加司机以及司机-公司关系 信息
	 * @param request
	 * @param driverDto 司机信息
	 * @return
	 */
	@RequestMapping(value="/driver/addToDriverAndDriverComnumInfo.htm", method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	@SystemControllerLog(description="增加司机")
	public String addToDriverAndDriverComnumInfo(HttpServletRequest request, DriverDto driverDto) {
		try {
			//获取当前主体
			Subject subject = SecurityUtils.getSubject();
			//判断用户是否拥有某一种角色，如果有root角色，则页面显示分站点下拉框
			boolean isRole = subject.hasRole("root");
			if (isRole) {	//这个地方需要改改了；直接判断有没有这个资源就行了，如果没有这个资源，即便是root角色的也不行
				String companyNum = driverDto.getComnumNum();
				this.driverService.addDriverAndDriverComnumInfo(driverDto, companyNum);
				return ViewDataUtil.buildSuccessJson("增加司机成功");
			}else {
				//是否拥有某一个资源
				boolean isPer = subject.isPermitted("driver:add");
				//如果有这个资源
				if (isPer) {
					//获取当前登录的用户信息
					SalesmanDto salesmanDto = (SalesmanDto) request.getSession().getAttribute(Const.TTBJ_USER_SESSION_KEY);
					System.out.println(JsonTools.GsonString(salesmanDto));
					//获取公司编号
					String companyNum = salesmanDto.getSalesmanComnum();
					this.driverService.addDriverAndDriverComnumInfo(driverDto, companyNum);
					return ViewDataUtil.buildSuccessJson("增加司机成功");
				}
			}
			return ViewDataUtil.buildFailureJson(1, "非法操作");
		} catch (BusinessException e) {
			return ViewDataUtil.buildFailureJson(e.getErrorCode(), e.getMessage());
		}
	}
	
	/**
	 * 只增加司机-关系的信息
	 * @param request
	 * @param driverDto 司机信息
	 * @return
	 */
	@RequestMapping(value="/driver/addToDriverComnumInfo.htm", method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	public String addToDriverComnumInfo(HttpServletRequest request, @RequestParam String driverName) {
		//获取当前登录的用户信息
		SalesmanDto salesmanDto = (SalesmanDto) request.getSession().getAttribute(Const.TTBJ_USER_SESSION_KEY);
		//获取公司编号
		String companyNum = salesmanDto.getSalesmanComnum();
		//使用长途司机用户名查询得到司机编号
		String driverNum = this.driverService.findDriverNumByName(driverName);
		//保存长途司机-公司 关系
		this.driverService.addDriverComnumInfo(driverNum, companyNum);
		return ViewDataUtil.buildSuccessJson("增加司机成功");
	}
	
	/**
	 * 删除司机 本质是删除司机-公司 关系
	 * @param request
	 * @param driverNum 司机编号
	 * @return
	 */
	@RequestMapping(value="/driver/delDriverInfo.htm", method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	public String delDriverInfo(HttpServletRequest request, @RequestParam String driverNum) {
		//获取当前登录的用户信息
		SalesmanDto salesmanDto = (SalesmanDto) request.getSession().getAttribute(Const.TTBJ_USER_SESSION_KEY);
		//获取公司编号
		String companyNum = salesmanDto.getSalesmanComnum();
		//执行删除关系
		this.driverService.delDriverAndComnum(driverNum, companyNum);
		return ViewDataUtil.buildSuccessJson("删除司机成功");
	}
	
	
	/**
	 * 通过司机的id查询审核需要用到的信息
	 * @param request
	 * @param driverId 司机id
	 * @return
	 */
	@RequestMapping(value="/driver/echoShortDriverInfo.htm", method=RequestMethod.GET, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	public String echoShortDriverInfo(HttpServletRequest request, @RequestParam Long driverId) {
		DriverDto driverDto = this.driverService.findDriverDetailsById(driverId);
		return ViewDataUtil.buildSuccessJson("短运司机信息", driverDto);
	}
	
	/**
	 * 司机审核
	 * @param request
	 * @param operation 操作：pass为审核通过，refuse为拒绝
	 * @param phone 手机号
	 * @param driverId 司机id
	 * @return
	 */
	@RequestMapping(value="/driver/toExamineEsendSms.htm", method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	public String toExamineEsendSms(HttpServletRequest request, @RequestParam String operation, 
								@RequestParam String phone, @RequestParam Long driverId, @RequestParam String realName) {
		try {
			if (StringUtils.isNotBlank(operation) && StringUtils.isNotBlank(phone) && StringUtils.isNotBlank(realName)) {
				JsonObject jsonObject = new JsonObject();
				jsonObject.addProperty("name", realName);
				int toExamineStatus = DriverToExamineEnum.under_review.getCode();
				if (operation.equals("pass")) {	//如果是点击通过
					jsonObject.addProperty("content", "已通过");
					toExamineStatus = DriverToExamineEnum.audit_pass.getCode();
				}else if (operation.equals("refuse")) { //如果是点击的拒绝
					jsonObject.addProperty("content", "未通过");
					toExamineStatus = DriverToExamineEnum.audit_failed.getCode();
				}else {
					return ViewDataUtil.buildFailureJson(PlatFormErrorCode.DATA_SECURITY.code(), "数据有误");
				}
				//给短运司机发送审核是否通过的信息，并获取返回码
				String code = ShortDriverSendSMSUtil.send(phone, jsonObject.toString());
				//如果成功给用户发送了信息，则进行数据修改
				if (StringUtils.isNotBlank(code) && code.equals("OK")) {
					//传入审核的状态值： 1为审核通过，2为审核未通过
					this.driverService.modifyDriverToExamine(toExamineStatus, driverId);
					return ViewDataUtil.buildSuccessJson("已审核");
				}
				return ViewDataUtil.buildFailureJson(PlatFormErrorCode.DATA_SECURITY.code(), "由于信息发送失败，请重新审核");
			}else {
				return ViewDataUtil.buildFailureJson(PlatFormErrorCode.DATA_SECURITY.code(), "数据有误");
			}
		} catch (ClientException | InterruptedException e) {
			return ViewDataUtil.buildFailureJson(PlatFormErrorCode.DATA_SECURITY.code(), "发送短信失败，请重新审核");
		}
	}
	
	/**
	 * 更改司机是否被禁用
	 * @param request
	 * @param driverNum 短运司机编号
	 * @return
	 */
	@RequestMapping(value="/driver/editDriverDisable.htm", method=RequestMethod.GET, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	@SystemControllerLog(description="修改司机是否禁用")
	public String editDriverDisable(HttpServletRequest request, @RequestParam String driverNum, @RequestParam Integer isDelete) {
		try {
			this.driverService.modifyDriverDisable(isDelete, driverNum);
			return ViewDataUtil.buildSuccessJson("修改成功");
		} catch (BusinessException e) {
			return ViewDataUtil.buildFailureJson(e.getErrorCode(), e.getMessage());
		}
	}
	
	/**
	 * 增加司机的时候发送给司机用户的验证码
	 * @param request
	 * @param phone 司机手机号
	 * @return
	 */
	@RequestMapping(value="/driver/send_verification_code.htm", method=RequestMethod.GET, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	public String send_verification_code(HttpServletRequest request, @RequestParam String phone) {
		//发送给司机用户验证码的位数
		int length = 5;
		try {
			//发送验证码操作
			this.driverService.sendSmsToDriver(phone, length);
			return ViewDataUtil.buildSuccessJson("发送成功");
		} catch (BusinessException e) {
			return ViewDataUtil.buildFailureJson(e.getErrorCode(), e.getMessage());
		}
	}
	
	/**
	 * 查询所有未删除（禁用）的司机的id和真实姓名
	 * @return
	 */
	@RequestMapping(value="/driver/getDriverIdAndRealName.htm", method=RequestMethod.GET, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	public String getDriverIdAndRealName() {
		List<DriverDto> driverDtos = this.driverService.findDriverIdAndRealName();
		return ViewDataUtil.buildSuccessJson("司机信息", driverDtos);
	}
	
	/**
	 * 查询未删除的所有司机和其对应公司的名字和id(用于预订单中分配司机)
	 * @return
	 */
	@RequestMapping(value="/driver/getDriverAndComInfo.htm", method=RequestMethod.GET, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	public String getDriverAndComInfo(HttpServletRequest request) {
		List<DriverDto> dtos = this.driverService.findDriverAndComInfo();
		return ViewDataUtil.buildSuccessJson("司机列表", dtos);
	}
}
